const {Builder, By, Key, until} = require('selenium-webdriver');
// const {Options} = require('selenium-webdriver/chrome');

// const options = new Options();

let result = []
let currentPage = 1

let driver = new Builder().forBrowser('chrome').build();
(async function start() {
    await driver.get('https://www.lagou.com/wn/zhaopin/');
    let renjiComplted = false
    let condition = async()=>driver.wait(until.elementTextContains(await driver.findElement(By.id("lg_tbar")),'刘乙江'),1000);
    while (!renjiComplted) {
        await driver.sleep(3000);//给用户三秒
        //刷新界面
        await condition().then(res=>{
            renjiComplted = true
        }).catch(()=>{
            renjiComplted = false
        })
    }
    await driver.sleep(2000);
    //此时已经登陆进入页面了
    await driver.findElement(By.css("a[data-lg-tj-id='4s00']")).click();//点击招聘按钮
    await driver.sleep(2000);
    await driver.findElement(By.css('#keyword')).sendKeys('前端', Key.RETURN);
    await driver.sleep(2000);
    await getData()
    console.log("result::::::::::::",result)
})();

async function getData(){
    console.log("正在爬取第"+currentPage+"页数据~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
    let itemsDiv = await driver.findElements(By.css('#jobList>div:nth-of-type(1)>div'));
    //迭代数组，获取我们所需要的数据
    for (let i = 0; i < itemsDiv.length; i++) {
        let item = itemsDiv[i];
        let title = await item.findElement(By.css('#openWinPostion')).getText();
        // let company = await item.findElement(By.css('.jobList .add em')).getText();
        // let time = await item.findElement(By.css('.jobList .format-time')).getText();
        // let position_link = await item.findElement(By.css('.jobList .position_link')).getAttribute('href')
        
        // let money = await item.findElement(By.css('.jobList .money')).getText();
        // let background = await item.findElement(By.css('.jobList .li_b_l')).getText();
        // background = background.replace(money,'')
        // let company_name = await item.findElement(By.css('.jobList .company_name')).getText();
        // let company_name_a = await item.findElement(By.css('.jobList .company_name a')).getAttribute('href')
        // let industry = await item.findElement(By.css('.jobList .industry')).getText();
        console.log("title::::::::::::",title)
        result.push(title)
    }
    let nextPageButton = await driver.findElement(By.css("li[title='下一页']>a"));
    //console.log("nextPageButton::::::::::::",nextPageButton.getAttributeNames())
    if(nextPageButton.getAttributeNames().indexOf('disabled')>-1){
        console.log("爬完~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
    }else{
        console.log("没爬完。继续爬~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
        await nextPageButton.click()
        await driver.sleep(1000)
        currentPage++
        await getData()
        
    }
}